import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Ulist from '../components/users/Ulist.vue'
import Urole from '../components/users/Urole.vue'
import Slist from '../components/sympthom/Slist.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' }, // 路由重定向
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      // 父组件中加入路由占位符，然后在父路由中定义子路由规则，如此搭配使用
      { path: '/welcome', component: Welcome },
      { path: '/ulist', component: Ulist },
      { path: '/role', component: Urole },
      { path: '/slist', component: Slist }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂在路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  // 如果不是去登陆页，判断token是否存在
  const tokenStr = window.sessionStorage.getItem('token')
  // 不存在，直接回到登陆页
  if (!tokenStr) return next('/login')
  // 存在，就进去
  next()
})

export default router
